package com.hzjy.quartz.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.hzjy.quartz.task.BackupTask;
import com.hzjy.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MysqlBackupUtil {
    static final Logger log = LoggerFactory.getLogger(BackupTask.class);

    /**
     * mysqldump 定时备份表格
     * @param host 数据库地址
     * @param dbName 数据库名,只备份表格的话只需要在后面加上空格+表名
     * @param account 用户名
     * @param pass 密码
     * @param savaPath 保存路径
     * @return
     */
    public static boolean  backupData(String host,String dbName,String account,String pass,String savaPath){
        Long starttime=System.currentTimeMillis();
        Runtime rt=Runtime.getRuntime();
        Process process;
        try {
            String command="mysqldump -h "+host+" -u "+account+" -p"+pass+" "+dbName+" --result-file "+savaPath+ DateUtils.getDates()+".sql";
            log.info("mysqldump running this comman-->"+command);
            process = rt.exec(command);
            if(process.waitFor()==0){
                log.info("mysqldump backup successfully");
                Long endtime=System.currentTimeMillis();
                Long distance=starttime-endtime;
                log.info("mysqldump备份花"+distance/1000+"秒");
                return true;

            }else{
                log.info("process.waitFor()!=0");
                InputStream is=process.getErrorStream();
                if(is!=null){
                    BufferedReader in=new BufferedReader(new  InputStreamReader(is,"utf-8"));
                    String line;
                    while((line=in.readLine())!=null){
                        log.error("mysqldump错误日志>"+line);
                    }
                }
            }
        }catch (Exception e) {
            log.info("mysqldump backup failed");
            e.printStackTrace();
            return false;
        }
        return false;

    }

}